package com.njwb.day16.dom.service.impl;

import com.njwb.day16.dom.dao.AccountDao;
import com.njwb.day16.dom.dao.impl.AccountDaoImpl;
import com.njwb.day16.dom.pojo.Account;
import com.njwb.day16.dom.service.AccountService;
import com.njwb.day16.dom.ts.ITransaction;
import com.njwb.day16.dom.ts.impl.TransactioImpl;
import com.njwb.day16.dom.util.DbUtil;

import java.sql.SQLException;
import java.util.List;

public class AccountServiceImpl implements AccountService {
    private AccountDao accountDao  = new AccountDaoImpl();

    private ITransaction transaction = new TransactioImpl() ;
    @Override
    public List<Account> queryAll() {
        try {
            return accountDao.queryAll();
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }finally {
            try {
                DbUtil.closeConnection();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }


    //一般情况下，如果一个业务操作涉及更新，需要添加事务，事务开启在服务层。

    @Override
    public void transMoney(String me, String obj, int money) {
        try {

            //事务的开启
            transaction.begin();
            Account meAccount = accountDao.findAccountById(me);
            Account objAccount = accountDao.findAccountById(obj);
            System.out.println("转账之前张三"+meAccount);
            System.out.println("转账之前lisi"+objAccount);

            meAccount.setBlance(meAccount.getBlance()-money);
            objAccount.setBlance(objAccount.getBlance()+money);

            accountDao.updateAccount(meAccount);
            //模拟断电
            //System.out.println(10/0);
            accountDao.updateAccount(objAccount);
            System.out.println("转账之后张三"+meAccount);
            System.out.println("转账之后lisi"+objAccount);

            transaction.commit();
            System.out.println("数据提交了");
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("数据回滚了");
            transaction.rollback();
        }finally {
            try {
                DbUtil.closeConnection();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
